package com.zhihu.service.impl;

import com.zhihu.pojo.Question;
import com.zhihu.pojo.baseVo.BaseResult;
import com.zhihu.pojo.req.SolrSearchQues;
import com.zhihu.service.SolrService;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class SolrServiceImpl implements SolrService {

    @Autowired
    HttpSolrClient httpSolrClient;
    /**
     * 默认展示当前的最热问题
     * @return 问题结果集
     */
    @Override
    public BaseResult findHotTopic() {

        //创建一个搜索对象
        SolrQuery solrQuery = new SolrQuery();
        BaseResult baseResult = new BaseResult();
        ArrayList<Question> list = new ArrayList<Question>();
        //设置搜索条件
        solrQuery.setQuery("*:*");
        //设置默认搜索域
        solrQuery.set("df","ques_title");
        //开启高亮展示
        solrQuery.setHighlight(true);
        //设置高亮展示域
        solrQuery.addHighlightField("ques_title");
        //设置高亮标签前缀
        solrQuery.setHighlightSimplePre("<font style='color:red'>");
        //设置高亮标签后缀
        solrQuery.setHighlightSimplePost("</font>");

        try {
            //根据query查询索引库
            QueryResponse queryResponse = httpSolrClient.query(solrQuery);

            if (queryResponse != null) {
                //得到高亮数据
                Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
                if (highlighting != null && highlighting.size() > 0) {

                    //取查询结果
                    SolrDocumentList solrDocumentList = queryResponse.getResults();
                    if (solrDocumentList != null) {
                        //取查询结果总记录数
                        long numFound = solrDocumentList.getNumFound();
                        baseResult.setCount(numFound);
                        List<SolrSearchQues> beans = queryResponse.getBeans(SolrSearchQues.class);

                        if (beans != null && beans.size() > 0) {

                            for (SolrSearchQues solrSearchQues : beans) {
                                //获取高亮的问题对象
                                Map<String, List<String>> stringListMap = highlighting.get(solrSearchQues.getQuestionId());

                                //标题和内容中同时存在关键字
                                String quesTitle1 = stringListMap.get("ques_title").get(0);

                                if(quesTitle1 !=null && !quesTitle1.equals("")){
                                    solrSearchQues.setQuesTitle(quesTitle1);
                                }

                                //将solrSearchQues中的参数放入新集合中
                                //在高并发高流量的网站使用Int或许不够，应该使用Long
                                int questionId = Integer.parseInt(solrSearchQues.getQuestionId());
                                int quesCommNums = Integer.parseInt(solrSearchQues.getQuesCommNums().toString());
                                int quesLikeNum = Integer.parseInt(solrSearchQues.getQuesLikenum().toString());

                                Question question = new Question();
                                question.setQuestionId(questionId);
                                question.setQuesCommNums(quesCommNums);
                                question.setQuesLikeNum(quesLikeNum);
                                question.setQuesInfo(solrSearchQues.getQuesInfo());
                                question.setQuesTitle(solrSearchQues.getQuesTitle());
                                question.setQuesImg(solrSearchQues.getQuesImg());
                                question.setOpusTap(solrSearchQues.getOpusTap());
                                question.setQuesCreatetime(solrSearchQues.getQuesCreatetime());
                                question.setQuesVio(solrSearchQues.getQuesVio());
                                question.setQuesUserImg(solrSearchQues.getQuesUserimg());
                                question.setQuesUserName(solrSearchQues.getQuesUsername());
                                question.setUserId(solrSearchQues.getUserId());

                                Date date = new Date();
                                Date date1=new Date(date.getTime()-24*60*60*1000);
                                if(question.getQuesCreatetime().before(date) && question.getQuesCreatetime().after(date1)){
                                        list.add(question);
                                }
                            }
                            //按照评论数排序，冒泡排序，大的永远放在右边
                            for(int i=0;i<list.size();i++){
                                for(int j=1;j<list.size()-i;j++){
                                    Question question = list.get(j - 1);
                                    Question question1 = list.get(j);
                                    if( (question1!=null) && (question.getQuesCommNums()>question1.getQuesCommNums()) ){
                                       list.set(j, question);
                                       list.set(j-1,question1);
                                    }
                                }
                            }
                            //新建目标数组
                            String[] strings = new String[5];
                            //倒序遍历
                            ListIterator<Question> questionListIterator = list.listIterator();
                            //倒序遍历拿出数据，放入string的集合
                            int count=0;
                            while(count<5 && questionListIterator.hasPrevious()){
                                Question previous = questionListIterator.previous();
                                String quesTitle = previous.getQuesTitle();
                                strings[count]=quesTitle;
                                count++;
                            }
                            baseResult.setData(strings);
                        }
                    }
                }
            }
            baseResult.setCode(1);
            baseResult.setMsg("查询成功！");
            return baseResult;
        } catch(Exception e){
            e.printStackTrace();
        }
        baseResult.setCode(0);
        baseResult.setMsg("查询失败！");
        return baseResult;
    }

    /**
     * 根据关键字搜索与关键字相关的问题
     * @return
     */
    @Override
    public BaseResult findQuesByKeyword(String keyword) {
        //创建一个搜索对象
        SolrQuery solrQuery = new SolrQuery();
        BaseResult baseResult = new BaseResult();
        ArrayList<Question> list = new ArrayList<Question>();
        //设置搜索条件
        solrQuery.setQuery("keyword");
        //设置默认搜索域
        solrQuery.set("df","ques_title");
        solrQuery.set("df","ques_info");
        //开启高亮展示
        solrQuery.setHighlight(true);
        //设置高亮展示域
        solrQuery.addHighlightField("ques_title");
        solrQuery.addHighlightField("ques_info");
        //设置高亮标签前缀
        solrQuery.setHighlightSimplePre("<font style='color:red'>");
        //设置高亮标签后缀
        solrQuery.setHighlightSimplePost("</font>");

        try {
            //根据query查询索引库
            QueryResponse queryResponse = httpSolrClient.query(solrQuery);

            if (queryResponse != null) {
                //得到高亮数据
                Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
                if (highlighting != null && highlighting.size() > 0) {

                    //取查询结果
                    SolrDocumentList solrDocumentList = queryResponse.getResults();
                    if (solrDocumentList != null) {
                        //取查询结果总记录数
                        long numFound = solrDocumentList.getNumFound();
                        baseResult.setCount(numFound);
                        List<SolrSearchQues> beans = queryResponse.getBeans(SolrSearchQues.class);

                        if (beans != null && beans.size() > 0) {

                            for (SolrSearchQues solrSearchQues : beans) {
                                //获取高亮的问题对象
                                Map<String, List<String>> stringListMap = highlighting.get(solrSearchQues.getQuestionId());

                                //标题和内容中同时存在关键字
                                String quesTitle1 = stringListMap.get("ques_title").get(0);
                                String quesInfo1 = stringListMap.get("ques_info").get(0);

                                if(quesTitle1 !=null && !quesTitle1.equals("")){
                                    solrSearchQues.setQuesTitle(quesTitle1);
                                }
                                if(quesInfo1 !=null && !quesInfo1.equals("")){
                                    solrSearchQues.setQuesInfo(quesInfo1);
                                }

                                //将solrSearchQues中的参数放入新集合中
                                //在高并发高流量的网站使用Int或许不够，应该使用Long
                                int questionId = Integer.parseInt(solrSearchQues.getQuestionId());
                                int quesCommNums = Integer.parseInt(solrSearchQues.getQuesCommNums().toString());
                                int quesLikeNum = Integer.parseInt(solrSearchQues.getQuesLikenum().toString());

                                Question question = new Question();
                                question.setQuestionId(questionId);
                                question.setQuesCommNums(quesCommNums);
                                question.setQuesLikeNum(quesLikeNum);
                                question.setQuesInfo(solrSearchQues.getQuesInfo());
                                question.setQuesTitle(solrSearchQues.getQuesTitle());
                                question.setQuesImg(solrSearchQues.getQuesImg());
                                question.setOpusTap(solrSearchQues.getOpusTap());
                                question.setQuesCreatetime(solrSearchQues.getQuesCreatetime());
                                question.setQuesVio(solrSearchQues.getQuesVio());
                                question.setQuesUserImg(solrSearchQues.getQuesUserimg());
                                question.setQuesUserName(solrSearchQues.getQuesUsername());
                                question.setUserId(solrSearchQues.getUserId());

                                list.add(question);
                                System.out.println(list.toString());
                            }
                            baseResult.setData(list);
                        }
                    }
                }
            }
            baseResult.setCode(1);
            baseResult.setMsg("查询成功！");
            return baseResult;
        } catch(Exception e){
            e.printStackTrace();
        }
        baseResult.setCode(0);
        baseResult.setMsg("查询失败！");
        return baseResult;
    }
}
